<template>
  <!-- 订单管理 -->
  <div>
    <template v-if="!ishome">
      <div class="flexbox_row">
        <div class="flex1">
          <el-row>
            <el-col :span="24">
              <el-form :inline="true" :model="searchInfo">
                <el-form-item class="mleft10 mb0" label="仓库:">
                  <el-select v-model="searchInfo.code" clearable class="w200px" placeholder="请选择">
                    <el-option
                      v-for="ele in warehouseList"
                      :key="ele.code"
                      :label="ele.name"
                      :value="ele.code"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class="mleft10 mb0" label="运输方式:">
                  <el-select v-model="searchInfo.ship_type" clearable class="w200px" placeholder="请选择">
                    <!-- 0:公路运输,1:铁路运输,2:水路运输,3:航空运输,4:管道运输 -->
                    <el-option label="公路运输" value="0"></el-option>
                    <el-option label="铁路运输" value="1"></el-option>
                    <el-option label="水路运输" value="2"></el-option>
                    <el-option label="航空运输" value="3"></el-option>
                    <el-option label="管道运输" value="4"></el-option>
                  </el-select>
                </el-form-item>

                <!-- <el-form-item class="mleft10 mb0"
                              label="目的地:">
                  <el-select v-model="searchInfo.warehouse_code"
                             clearable
                             class="w200px"
                             placeholder="请选择">
                    <el-option v-for="ele in warehouseList"
                               :key="ele.code"
                               :label="ele.name"
                               :value="ele.code"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="创建时间:"
                              prop="times"
                              class="mleft10 mb0">
                  <el-date-picker v-model="searchInfo.times"
                                  type="datetimerange"
                                  range-separator="-"
                                  class="w350px"
                                  start-placeholder="开始时间"
                                  end-placeholder="结束时间"
                                  @change="searchInfo.times = $changeTime($event)"></el-date-picker>
                </el-form-item> -->

                <el-form-item class="mb0">
                  <el-button type="primary" icon="Search" @click="getListDataHandler">查询</el-button>
                  <el-button type="warning" icon="Delete" @click="clearSearch">清空</el-button>

                  <el-dropdown class="mleft10" trigger="click" :disabled="exportXSLing" @command="OtherFu">
                    <el-button type="primary" plain>
                      其他功能<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="export" icon="el-icon-download">导出</el-dropdown-item>

                      <el-dropdown-item command="upload" icon="el-icon-upload2">导入</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>

        <div class="addbox" v-if="tagIndex == 1">
          <el-button type="success" size="default" @click="addModal('add')" icon="el-icon-plus">创建订单</el-button>
        </div>
      </div>

      <el-main style="padding: 0 !important">
        <div class="wh100">
          <el-table
            :data="tableDataList"
            stripe
            v-loading="loadings"
            border
            highlight-current-row
            class="wh100"
            tooltip-effect="dark"
            :height="tabelHeight(335)"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              v-for="(item, index) in tableColumn"
              :key="index"
              :width="item.width || ''"
              :type="item.type || ''"
              :prop="item.key || ''"
              header-align="center"
              :align="item.align || 'center'"
              show-overflow-tooltip
              :fixed="item.fixed || false"
              :sortable="item.sortable || ''"
              :label="item.title || ''"
              :minWidth="item.minWidth || ''"
              :filter-method="item.filterRender"
              :index="item.index"
            >
              <template #default="scope" v-if="item.type !== 'selection' && item.type !== 'index'">
                <template v-if="item.render">
                  <cl-expand :column="item" :row="scope.row" :render="item.render" :index="index" />
                </template>

                <template v-else-if="item.type !== 'selection'">
                  <span>{{ scope.row[item.key] || '' }}</span>
                </template>
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              width="200"
              align="center"
              fixed="right"
              v-if="tagIndex == 0 || tagIndex == 1"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="changeEdit('edit', scope.row)"
                  v-if="tagIndex == 1"
                  >修改</el-button
                >

                <el-button
                  type="danger"
                  v-if="tagIndex == 0 || tagIndex == 1"
                  icon="el-icon-delete"
                  :disabled="scope.row.status == 2"
                  @click="changeEdit('delete', scope.row)"
                  >{{ tagIndex == 0 ? '删除' : '作废' }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>

      <el-footer class="footsPadding0 flex_row_space-between">
        <div class="foot-operation">
          <el-button
            size="medium"
            type="primary"
            v-if="tagIndex == 1"
            @click="dialogVisible = true"
            :disabled="!selectIds.length"
            >批量审核</el-button
          >
          <el-button
            size="medium"
            class="mleft10"
            type="danger"
            icon="el-icon-delete"
            @click="toVoid"
            v-if="tagIndex == 0 || tagIndex == 1"
            :disabled="!selectIds.length"
            >批量{{ tagIndex == 0 ? '删除' : '作废' }}</el-button
          >
        </div>

        <div>
          <cl-pagination :paging-info="pagingInfo" @size_current_change="sizeCurrentChange" />
        </div>
      </el-footer>
    </template>

    <add-model
      v-else
      @close="addModal"
      :warehouseList="warehouseList"
      :show-model.sync="ishome"
      :info-model="rowData"
    />

    <dialog-modal :show-modal.sync="dialogVisible" @success="toExamineHandler" @close="dialogVisible = false" />

    <upload :show-modal.sync="showUpload" @get-data="getListDataHandler" />
  </div>
</template>
<script>
import API from '@/api/order.js'
import { columnsTitle } from './column.js'
import mixins from '@/component-cl/mixins/mixins'
import ClExpand from '@/component-cl/expand/expand'
import { getTruthyParams, dowloadFileResFunction } from '@/libs/common.js'

export default {
  name: 'OrderInfo',
  mixins: [mixins],

  components: {
    ClExpand,
    dialogModal: () => import('@/component-cl/dialog/dialog.vue'),
    AddModel: () => import('./add-info.vue'),
    Upload: () => import('./upload.vue'),
  },

  props: {
    tagIndex: {
      type: String,
      default: '',
    },
  },

  watch: {
    tagIndex: {
      handler(val) {
        console.log(val, '=========185')
        this.getListDataHandler()

        if (!this.warehouseList.length) {
          this.getWarehouseHandler()
        }
      },
      deep: true,
      immediate: true,
    },
  },

  data() {
    return {
      ishome: false,
      searchInfo: {},
      selectIds: [],
      warehouseList: [],
      rowData: {},
      exportXSLing: false,
      dialogVisible: false,
      showUpload: false,
      cloumnArr: columnsTitle(this),
    }
  },

  computed: {
    tableColumn() {
      let list = this.cloumnArr
      list = list.filter(e => !e.hide)
      return list
    },
  },

  methods: {
    /**
     *审核
     */
    async toExamineHandler(type) {
      const selectIds = []
      this.selectIds.forEach(ele => {
        selectIds.push(ele.id)
      })
      try {
        const params = {
          id_list: selectIds,
          status: type,
        }
        const RES = await API.toExamine_Order(params)
        console.log(RES)
        if (RES.code == 2) {
          this.$message({
            message: '成功',
            type: 'success',
          })
          this.dialogVisible = false

          this.getListDataHandler()
        } else {
          this.$message({
            message: '失败',
            type: 'warning',
          })
        }
      } catch (error) {
        this.dialogVisible = false
        this.$message({
          message: '网络异常/失败',
          type: 'warning',
        })
      }
    },
    /**
     * 仓库
     */
    async getWarehouseHandler() {
      try {
        const RES = await API.getWarehouseList()
        console.log(RES, '仓库')
        this.warehouseList = RES.data || []
      } catch (error) {
        console.log(error)
      }
    },

    sortChange() {
      this.cloumnArr = this.cloumnArr.map(ele => {
        if (ele.hide) {
          ele.hide = false
        }
        return ele
      })
    },

    async getListDataHandler() {
      const { curr_page, page_size } = this.pagingInfo
      let params = {
        curr_page,
        page_size,
      }

      if (this.tagIndex !== '-1' && this.tagIndex) {
        params.inboundOrderStatus = this.tagIndex
      }

      params = this.filterSearchData(params)
      try {
        this.loadings = true
        const RES = await API.getOrderList(params)
        console.log(RES.items)
        const { total = 0, items = [] } = RES || {}
        this.tableDataList = items
        this.pagingInfo.total = total
        this.selectIds = []
        this.loadings = false
      } catch (error) {
        console.log(error)
        this.loadings = false
        this.$message({
          message: '网络异常/请稍后重试',
          type: 'warning',
        })
      }
    },

    // 新增
    addModal(type = false) {
      if (type === 'close') {
        this.ishome = false
        this.getListDataHandler()
        this.$emit('disabled-handler', false)
      } else {
        this.$emit('disabled-handler', true)

        this.rowData = {
          isAdd: 'add',
          products: [{ sku: '', name: '' }],
        }
        this.ishome = true
      }
    },

    // exportXSLing () { },

    async changeEdit(e, data) {
      console.log(data)
      if (e == 'delete') {
        this.toVoid(data)
      } else if (data.order_no) {
        try {
          const RES = await API.getEditOrderDetail(data.order_no)
          console.log(RES, '=============X详情参数')
          this.rowData = {
            ...RES,
            isAdd: 'edit',
          }
          this.rowData.create_type = RES.create_type ? String(RES.create_type) : ''
          this.rowData.order_type = RES.order_type || RES.order_type == 0 ? String(RES.order_type) : ''
          this.rowData.ship_type = RES.ship_type || RES.ship_type == 0 ? String(RES.ship_type) : ''
          this.rowData.container_type = RES.container_type || RES.container_type == 0 ? String(RES.container_type) : ''
          this.$emit('disabled-handler', true)

          this.ishome = true
        } catch (error) {
          console.log(error, '获取详情失败')
        }
      } else {
        this.$message({
          message: '缺少修改功能的必须：order_no',
          type: 'warning',
        })
      }
    },

    // 多选操作
    handleSelectionChange(e) {
      this.selectIds = e
    },

    OtherFu(e) {
      if (e == 'export') {
        this.$confirm('确定导出产品信息？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          this.confirmExport()
        })
      } else if (e == 'upload') {
        this.showUpload = true
      }
      //  else if (e == 'editable') {
      //   this.showEditTable = true
      // }
    },

    /**
     * 导出
     */
    async confirmExport() {
      try {
        this.exportXSLing = true
        const RES = await API.exportProductFile(1)
        console.log(RES, '================')

        dowloadFileResFunction({ file: RES, fileName: '单个产品数据', status: RES ? 200 : 404 })
        this.exportXSLing = false
      } catch (error) {
        this.exportXSLing = false

        this.$message({
          message: '网络异常/导出失败',
          type: 'warning',
        })
      }
    },

    filterSearchData(params) {
      const data = getTruthyParams(this.searchInfo)

      if (data.times && data.times.length) {
        const [begin_time, end_time] = data.times
        params.begin_time = begin_time
        params.end_time = end_time
        delete data.times
      }
      return { ...data, ...params }
    },

    /**
     * 作废
     */
    toVoid(data = false) {
      const selectIds = []
      this.selectIds.forEach(ele => {
        if (ele.status == 1) {
          selectIds.push(ele.id)
        }
      })

      let msg = '确定作废已勾选产品吗？'
      if (data && data.id) {
        msg = '确定作废此单吗？'
      }

      // 真删
      if (this.tagIndex == 0) {
        msg = '确定删除已勾选订单吗？'
        if (data && data.id) {
          msg = '确定删除此单吗？'
        }
      }
      this.$confirm(msg, '温馨提示', {
        confirmButtonText: '作废',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          let ids = []
          let res = null
          if (data && data.id) {
            ids = [data.id]
          } else {
            ids = selectIds
          }

          if (this.tagIndex == 0) {
            // 真删
            res = await API.reallyDelete_Order({ id_list: ids })
          } else {
            res = await API.soft_delete_Order({ id_list: ids })
          }

          console.log(res)
          if (res.code == 3) {
            this.$message({
              message: '成功',
              type: 'success',
            })
            this.getListDataHandler()
          } else {
            this.$message({
              message: '失败',
              type: 'warning',
            })
          }
        } catch (error) {
          this.$message({
            message: '网络异常/失败',
            type: 'warning',
          })
        }
      })
    },
  },

  // mounted () {
  //   this.getWarehouseHandler()
  // }
}
</script>
